import { memo, useEffect, useRef } from "react";
import { IndicatorWrapper } from "./style";

export const Indicator = memo(
    (props) => {
        //获取传入的index
        const { selectIndex } = props;
        const contentRef = useRef();
        useEffect(() => {
            //计算移动的距离
            console.log("selectIndex:", selectIndex);
            const selectItem = contentRef.current.children[selectIndex]; 
            console.log("selectItem", selectItem);
            const offsetLeft = selectItem.offsetLeft;
            const itemWidth = selectItem.clientWidth;
            const contentWidth = contentRef.current.clientWidth;

            //计算要移动的距离
            let  distance = offsetLeft + itemWidth * 0.5 - contentWidth * 0.5;
            //移动
            const totalDistance = contentRef.current.scrollWidth - contentWidth;
            if (distance < 0 || distance > totalDistance) distance = 0;
            contentRef.current.style.transform = `translate(${-distance}px)`
            console.log(offsetLeft,itemWidth,contentWidth,distance);  
        },[selectIndex])

        return (
            <IndicatorWrapper>
                <div className="i-content" ref={contentRef}>
                   {props.children}
                </div>
            </IndicatorWrapper>
        )
    }
)